<!DOCTYPE html>
<html lang="en">
  <head>
    <title>option页面</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="../css/style.css" rel="stylesheet">
    <link href="../css/option.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
  </head>
  <body>
    <div id="app">
      <div class="app-container">
        <el-upload
        class="avatar-uploader"
        :action= "uploadUrl"
        :headers="myHeaders"
        accept=".jpg, .png"
        :show-file-list="false"
        :on-success="handleIconSuccess"
        :before-upload="beforeIconUpload">
        <img v-if="imageUrl != ''" :src="imageUrl" class="avatar">
        <el-button type="primary" v-else size="small">上传图片</el-button>
      </el-upload>
      </div>
    </div>
    <a href="../index.html">去首页</a>

    <script>
      new Vue({
        el: "#app",
        data() {
          return {
            uploadUrl: "http://localhost:3000/api/upload/image",
            myHeaders: {token: sessionStorage.getItem("token")},
            // 图片验证
            imageFlag: true,
            maxImage: true,
            //icon的url
            imageUrl: '',
            token: undefined
          }
        },
        created () {
          this.token = sessionStorage.getItem("token")
          if (!this.token) {
            sessionStorage.clear()
            window.location.href = "/login.html"
            return
          }
        },
        methods: {
          // 上传图片
          handleIconSuccess(res, file) {
            if (res.code == 400) {
              sessionStorage.clear()
              window.location.href = "/login.html"
            }
            console.log(res)
            if (this.maxImage == true && this.imageFlag == true) {
              this.imageUrl = res.data.objectUrl
            }
          },
          beforeIconUpload (file) {
            this.maxImage = true
            this.imageFlag = true
            const image = file.name.substring(file.name.lastIndexOf('.')+1)
            const detail = image === 'jpg'
            const detail2 = image === 'png'
            const isLt4M = file.size / 1024 / 1024 < 4
            if (!detail && !detail2) {
              this.imageFlag = false
              this.$message.error(`上传图片只能是 JPG 或 PNG 格式!`)
              return false
            }
            if (!isLt4M) {
              this.maxImage = false
              this.$message.error('上传图片大小不能超过 4MB!');
              return false
            }      
            return (detail2 || detail) && isLt4M
          }
        },
      })
    </script>
  </body>
</html>